package com.yjkf.zh.admin.controller;

import com.yjkf.zh.admin.aspect.LogAnnotation;
import com.yjkf.zh.admin.dao.SysUserMapper;
import com.yjkf.zh.admin.dao.SysUserRoleMapper;
import com.yjkf.zh.admin.model.SysDevice;
import com.yjkf.zh.admin.model.SysUser;
import com.yjkf.zh.admin.model.SysUserDevice;
import com.yjkf.zh.admin.model.SysUserRole;
import com.yjkf.zh.admin.security.SecurityUtils;
import com.yjkf.zh.admin.service.SysUserService;
import com.yjkf.zh.admin.util.LoginBean;
import com.yjkf.zh.admin.util.PasswordUtils;
import com.yjkf.zh.admin.util.SysConstant;
import com.yjkf.zh.core.http.HttpResult;
import com.yjkf.zh.core.page.PageRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("user")
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @GetMapping(value="/findAll")
    public Object findAll(){
       return sysUserService.findAll();
      //return "你好，项目！";
    }

    @PreAuthorize("hasAuthority('sys:user:view')")
    @PostMapping(value="/findPage")
   //LogAnnotation(content = "查询用户列表")
    public HttpResult findPage(@RequestBody PageRequest pageRequest){

        System.out.println(SecurityUtils.getUsername());

      // Long userId = (Long)request.getSession().getAttribute("userId");

        return HttpResult.ok(sysUserService.findPageBy(pageRequest));
    }

    @PreAuthorize("hasAuthority('sys:user:add') AND hasAuthority('sys:dict:edit')")
    @PostMapping("/iou")
    @LogAnnotation(content = "修改或添加用户操作")
    public HttpResult insertOrUpdate(@RequestBody SysUser sysUser){
        SysUser sysUser1 =sysUserService.findById(sysUser.getId());
        if(sysUser1!=null){
            if(SysConstant.ADMIN.equalsIgnoreCase(sysUser1.getUserName())){
                return HttpResult.error("工厂最高权限不能修改！");
            }
        }
        if(sysUser.getPassword() != null){
            String salt = PasswordUtils.getSalt();
            if(sysUser1 == null){
                //新增用户
                if(sysUserService.findByName(sysUser.getUserName())!=null){
                    return  HttpResult.error("用户名已经存在");
                }

                String password = PasswordUtils.encode(sysUser.getPassword(),salt);
                sysUser.setSalt(salt);
                sysUser.setPassword(password);
            }else{
                //修改用户，且修改了密码
                if(!sysUser.getPassword().equals(sysUser1.getPassword())){
                    String password = PasswordUtils.encode(sysUser.getPassword(),salt);
                    sysUser.setSalt(salt);
                    sysUser.setPassword(password);
                }
            }
        }
        return HttpResult.ok(sysUserService.save(sysUser));
    }

    /**
     * 删除用户
     */
    @PreAuthorize("hasAuthority('sys:user:delete')")
    @PostMapping(value = "/delete")
    @LogAnnotation(content = "删除用户操作")
    public HttpResult delete(@RequestBody List<SysUser> records){
        for(SysUser record:records){
            SysUser sysUser = sysUserService.findById(record.getId());
            if(sysUser!=null && SysConstant.ADMIN.equalsIgnoreCase(sysUser.getUserName())){
                return HttpResult.error("工厂权限不得删除！");
            }
            List<SysUser> sysUsers = sysUserMapper.findCreateId(sysUser.getId());
            if(!sysUsers.isEmpty()){
                return HttpResult.error("存在创建子用户账户，请联系删除！");
            }
        }
        return HttpResult.ok(sysUserService.delete(records));
    }

    @PreAuthorize("hasAuthority('sys:user:view')")
    @GetMapping(value = "/findPermissions")
    public HttpResult findPermissions(@RequestParam String userName){
        return HttpResult.ok(sysUserService.findPermissions(userName));
    }


    @PreAuthorize("hasAuthority('sys:user:view')")
    @PostMapping(value = "/upDevForUser")
    @LogAnnotation(content = "修改了用户设备绑定")
    public HttpResult findPermissions(@RequestBody List<SysUserDevice> records, HttpServletRequest request){
        Long selfId = (Long)request.getSession().getAttribute("userId");
        Long userId=null;
        for(SysUserDevice sysDevice:records){
            userId=sysDevice.getUserId();
        }
        return HttpResult.ok(sysUserService.upDevForUser(records,userId,selfId));
    }


    @GetMapping(value = "/updatePassword")
    @LogAnnotation(content = "更改了密码")
    public HttpResult updatePassword(@RequestParam String password, @RequestParam String newPassword) {
        SysUser user = sysUserService.findByName(SecurityUtils.getUsername());
        if(user == null) {
            HttpResult.error("用户不存在!");
        }
       if(SysConstant.ADMIN.equalsIgnoreCase(user.getUserName())) {
            return HttpResult.error("超级管理员不允许修改!");
        }
        if(!PasswordUtils.matches(user.getSalt(), password, user.getPassword())) {
            return HttpResult.error("原密码不正确!");
        }
        user.setPassword(PasswordUtils.encode(newPassword, user.getSalt()));
        return HttpResult.ok(sysUserService.updatePassword(user));
    }

    @GetMapping("/getUserId")
    public HttpResult getUserId(HttpServletRequest request){
        Long userId = (Long)request.getSession().getAttribute("userId");
        return HttpResult.ok(userId);
    }

    @GetMapping("/getUserSelf")
    public HttpResult getUserDb(@RequestParam String userName){
        //根据用户名获取用户信息
        SysUser sysUser = sysUserService.findByName(userName);
        SysUserRole sysUserRole = sysUserRoleMapper.findByUserId(sysUser.getId());
        if(sysUserRole!=null) {
            sysUser.setRoleId(sysUserRole.getRoleId());
        }
        return HttpResult.ok(sysUser);
    }

    //获取自己创建的全部用户
    @GetMapping("/getUsersForMe")
    public HttpResult getUsersForMe(HttpServletRequest request){
        Long userId = (Long)request.getSession().getAttribute("userId");
        return HttpResult.ok(sysUserMapper.findCreateId(userId));
    }
}
